package com.eagle.epay.controller;


import com.eagle.epay.common.ResultVO;
import com.eagle.epay.exception.ServiceException;
import com.eagle.epay.util.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @Author：eagle liu
 * @Description：Handle global controller exception. @CreateDate：08:16 AM
 *                     2019/08/17
 */
@ControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResultVO<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		BindingResult bindingResult = e.getBindingResult();
		return ResultVOUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
	}

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResultVO<?> handleGenericException(Exception e) {
		log.error(e.getMessage(), e);
		return ResultVOUtil.error(e.getMessage());
	}

	@ExceptionHandler(ServiceException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResultVO<?> handleBizException(Exception e) {
		// TODO: maybe need some special handle here?
		log.error(e.getMessage(), e);
		return ResultVOUtil.error(e.getMessage());
	}
}
